<?php
/**
 * Note: 应用渠道
 * Date: 2020/4/26
 */
namespace App\Http\Controllers\Admin;

use App\Models\Game\Center\AppSource;
use App\Models\Game\Center\AppSourceConfig;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AppSourceController extends CurdController
{
    protected string $classModel = AppSource::class;

    protected array $searchFields = [
        'name' => self::FIELD_TYPE_LIKE,
        'type' => self::FIELD_TYPE_NUMERIC,
        'os' => self::FIELD_TYPE_NUMERIC,
        'status' => self::FIELD_TYPE_NUMERIC,
    ];

    protected array $relationWiths = [
        'config:id,name',
    ];

    /**
     * 保存之前校验
     * @param Request $request
     */
    public function storeBefore(Request $request)
    {
        $request->validate([
            'id' => [
                'required',
                'int',
                Rule::unique('gameCenter.app_sources')->ignore($request->id),
            ],
            'name' => 'required|alpha_dash',
            'desc' => 'sometimes|string',
            'type' => 'sometimes|numeric',
            'os' => 'sometimes|numeric|in:0,1',
            'status' => 'sometimes|numeric',
        ]);
    }

    /**
     * 更新之前校验
     * @param Request $request
     */
    public function updateBefore(Request $request)
    {
        $request->offsetUnset('id');
        $request->validate([
            'name' => 'sometimes|alpha_dash',
            'desc' => 'sometimes|string',
            'type' => 'sometimes|numeric',
            'os' => 'sometimes|numeric|in:0,1',
            'status' => 'sometimes|numeric',
        ]);
    }

    /**
     * 保存之后
     * @param AppSource $appSource
     * @param Request $request
     */
    public function storeAfter(AppSource $appSource, Request $request)
    {
        $this->syncConfigs();
    }

    /**
     * @param AppSource $appSource
     * @param Request $request
     */
    public function updateAfter(AppSource $appSource, Request $request)
    {
        $this->syncConfigs();
    }

    /**
     *
     */
    public function syncConfigs()
    {
        $appSources = AppSource::get(['id', 'app_source_config_id']);
        $configs = [];
        foreach ($appSources as $appSource) {
            if (!$appSource->app_source_config_id) continue;
            if (empty($configs[$appSource->app_source_config_id])) {
                $configs[$appSource->app_source_config_id] = [];
            }
            array_push($configs[$appSource->app_source_config_id], $appSource->id);
        }

        if (empty($configs)) {
            return;
        }

        $appConfigs = AppSourceConfig::all();
        foreach ($appConfigs as $appConfig) {
            $appConfig->sources = $configs[$appConfig->id] ?? [];
            $appConfig->save();
        }
    }
}
